<template>
    
    <div style="background-color: #041c30">
    
        <div class="outer-container">
            <div class="search-form-panel">
                <el-form :model="searchData" label-width="120">
                    <el-form-item label="定制查询" prop="type">
                        <el-radio :value="0" v-model="searchData.type" style="width: 20px;"></el-radio>
                    </el-form-item>
                    <el-form-item label="开始时间" prop="valueStart">
                        <el-input-number :min="0" v-model="searchData.valueStart" :disabled="searchData.type === 1" style="width: 120px" />
                        <el-select v-model="searchData.unitStart" style="width: 80px" :disabled="searchData.type === 1">
                            <el-option v-for="(item, index) in TIME_UNIT" :key="index" :value="item.value" :label="item.label"></el-option>
                        </el-select>
                        <span style="margin-left: 4px;">前</span>
                    </el-form-item>
                    <el-form-item label="结束时间" prop="unitEnd">
                        <el-input-number :min="0" v-model="searchData.valueEnd" style="width: 120px" :disabled="searchData.type === 1" />
                        <el-select v-model="searchData.unitEnd" style="width: 70px" :disabled="searchData.type === 1">
                            <el-option v-for="(item, index) in TIME_UNIT" :key="index" :value="item.value" :label="item.label"></el-option>
                        </el-select>
                        <span style="margin-left: 4px;">前</span>
                    </el-form-item>
                    <el-form-item label="数据间隔">
                        <el-input-number :min="0" v-model="searchData.value" style="width: 120px"></el-input-number>
                        <el-select v-model="searchData.unit" style="width: 70px">
                            <el-option v-for="(item, index) in TIME_UNIT" :key="index" :value="item.value" :label="item.label"></el-option>
                        </el-select>
                        <span style="margin-left: 4px;">前</span>
                    </el-form-item>
                    <el-form-item label="最小值"    style="display: none;">
                        <el-input-number :min="1" v-model="searchData.min" style="width: 140px" />
                    </el-form-item>
                </el-form>
                <el-form :model="searchData" label-width="120">
                    <el-form-item label="自定义查询">
                        <el-radio :value="1" v-model="searchData.type" style="width: 20px;"></el-radio>
                    </el-form-item>
                    <el-form-item label="开始时间">
                        <el-config-provider :locale="zhCn">
                            <el-date-picker v-model="timeRange" type="datetimerange" start-placeholder="开始时间" end-placeholder="结束时间" :disabled="searchData.type === 0" :default-time="[initStratTime, initEndTime]" style="width: 526px" format="YYYY-MM-DD HH:mm:ss" />
                        </el-config-provider>
                    </el-form-item>
                    <el-form-item label="特征值">
                        <el-select class="sdz-select" :teleported="false" v-model="searchData.sdzs" multiple collapse-tags clearable placeholder="请选择特征值" style="width: 209px">
                            <el-option v-for="(item, index) in sdzOptions" :value="index" :label="item.description" :key="index">
                                {{ item.description }}
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="最大值"   style="display: none;">
                        <el-input-number :min="1" v-model="searchData.max" style="width: 140px" />
                    </el-form-item>
                    <el-form-item label="">
                        <el-button type="primary" @click="searchHistoryData">查 询</el-button>
                    </el-form-item>
                </el-form>
            </div>
            <div class="echarts-panel" id="history_echarts" v-loading="loading">
            </div>
            <div class="result-table-panel">
                <div class="popover-container" v-show="popOverVisible" :style="poperStyle">
                    <span @click="toAddSDZ">添加</span>
                    <span @click="toDeleteSDZ">删除</span>
                </div>
                <el-table  v-loading="loading" ref="multipleTableRef" size="small" @row-click="changeMinMax" @row-contextmenu="addOrDelete" :data="resultTableData" :border="true" style="width: 80%; height: 200px;" @selection-change="handleSelectionChange">
                    <el-table-column type="selection" width="55" :align="'center'" />
                    <el-table-column prop="seq" label="序号" width="60" :align="'center'" />
                    <!-- <el-table-column prop="name" label="名称" width="200" /> -->
                    <el-table-column prop="description" label="描述" width="200" />
                    <el-table-column prop="unit" label="单位" width="80" />
                    <el-table-column prop="v" label="当前值" width="120" />
                    <el-table-column prop="avg" label="平均值" width="100" />
                    <el-table-column prop="cursorVal" label="光标值" width="100" />
                    <el-table-column prop="max" label="上限" width="120">
                        <template #default="{ row }">
                            <el-input v-model="row.max" size="small" @change="changeMinMax" />
                        </template>
                    </el-table-column>
                    <el-table-column prop="min" label="下限" width="120">
                        <template #default="{ row }">
                            <el-input v-model="row.min" size="small" @change="changeMinMax" />
                        </template>
                    </el-table-column>
                    <el-table-column prop="maxTime" label="最大值时刻" width="180" />
                    <el-table-column prop="minTime" label="最小值时刻" width="180" />
                </el-table>
                <el-dialog v-model="dialogVisible" width="450">
                    <el-form label-width="100" label-position="left" style=" padding-top: 10px;" label-suffix=":">
                        <el-form-item prop="filterValue" label="查找内容">
                            <el-input v-model="filterValue" placeholder="过滤" style="width: 200px"></el-input>
                            <el-button style="position: absolute; right: 20px;" type="primary" @click="toSearchSdz">查找</el-button>
                        </el-form-item>
                    </el-form>
                    <el-table ref="dialogTableComp" :data="dialogTableData" size="small" :border="true" style="height: 400px;">
                        <el-table-column type="selection" width="55" :align="'center'" />
                        <el-table-column prop="seq" label="序号" width="60" :align="'center'" />
                        <el-table-column prop="description" label="描述" width="200" />
                    </el-table>
                    <template #footer>
                        <div class="dialog-footer">
                            <el-button type="primary" @click="toConfirmDialog">确认</el-button>
                            <el-button @click="dialogVisible = false">取消</el-button>
                        </div>
                    </template>
                </el-dialog>
            </div>
        </div>
  
    </div>



    
    <div class="stage_t">
        <div class="stage_t_left">  
            <img src="../assets/logins.jpg" alt=""> <span>国能怀安热电有限公司</span>
       </div>
       <div  class="stage_t_zhong">燃烧数字化监测与可视化系统</div>
       <div  class="stage_t_right">
           <img src="../assets/timer.png" alt=""> <span>{{ nowTime }}</span>
       </div>
    </div>
    
</template>

<script setup>
import { ref, reactive, onMounted, nextTick, watch } from "vue";
import { formatTime, formatDate } from "../utils/date.js";
import { getSDZlist2, getSDZlist, history, searchSdz, history0 } from "../api/canshushezhi.js";
import * as echarts from "echarts";
import { ElMessage } from 'element-plus'
import { ElConfigProvider } from 'element-plus'
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'
    // Import stylesheet
    // import 'vue-loading-overlay/dist/vue-loading.css';
const nowTime = ref("");
const loading = ref(false);
const fullPage = ref(true);
// 获取当前日期
const today = new Date();
// 获取十天前的日期
const initStratTime = new Date(today);
initStratTime.setDate(today.getDate() - 10);

// 将十天前的日期设置为零时
initStratTime.setHours(0, 0, 0, 0);

// 获取今日的日期
const initEndTime = new Date(today);
// 将今日的日期设置为24时
initEndTime.setHours(23, 59, 59, 999);

const timeRange = ref([initStratTime, initEndTime])

const TIME_UNIT = [
    { value: 'd', label: '天' },
    { value: 'h', label: '时' },
    { value: 'm', label: '分' },
    { value: 's', label: '秒' },
]


let searchData = reactive({
    type: 0, //	默认定制查询0自定义查询1		
    valueStart: 0, //	定制追溯开始时间正整数		
    unitStart: "d", //	默认定制查询开始时间单位秒s分m时h天d，和自定义查询互斥（按钮置灰）		
    valueEnd: 0, //	定制追溯结束时间正整数		
    unitEnd: "d", //	默认定制查询结束时间单位秒s分m时h天d，和自定义查询互斥（按钮置灰）		
    value: 1, //	间隔数值正整数		
    unit: "h", //	查询间隔时间单位秒s分m时h天d		
    min: 0, //	过滤最小值		
    max: 2000, //	过滤最大值		
    sdzs: [],
});

const selectSDZArr = reactive([])

let myChart;
const serieData = reactive([])
const legendData = reactive([])
let timeoutCounter = -1

// watch(
//     () => searchData.sdzs.length,
//     (sdzs) => {
//         if (timeoutCounter !== -1) {
//             timeoutCounter = -1
//             clearTimeout(timeoutCounter)
//         }
//         timeoutCounter = setTimeout(function () {
//             timeoutCounter = -1
//             searchHistoryData()
//         }, 200)
//         // if (sdzs.length > 4) {
//         //     nextTick(() => {
//         //         ElMessage({
//         //             type: 'warning',
//         //             message: `SDZ最多只能选择4组数据`,
//         //         })
//         //     })
//         // }
//     }
// )


// 修改表格中的光标列
const changeValue = (arr) => {
    if (arr && arr.length > 0) {
        let selection = multipleTableRef.value.getSelectionRows()
        for (let i = 0; i < selection.length; i++) {
            if (arr[i] && arr[i].data) {
                selection[i].cursorVal = arr[i].data[1]
            } else {
                selection[i].cursorVal = ''
            }
        }
    }
}



const optionObj = {
    // 设置的是标题
    title: {
        text: '历史曲线'
    },
    tooltip: {
        trigger: 'axis',
        formatter: (c) => {
            let str = ''
            let temp = {
                showTime: '', // 时间
                marker: '', // 颜色
                seriesName: '', // legend名称
                valueData: '', // 数值
                setWidthSpan: '',
            }
            c.forEach((item) => {
                temp.showTime = item.data[0]
                temp.marker = item.marker
                temp.seriesName = item.seriesName
                temp.valueData = item.value[1]
                temp.setWidthSpan = '<span style="display:inline-block;width:10px;height:10px;"></span>'
                str += temp.marker + temp.seriesName + temp.setWidthSpan + temp.valueData + '<br />'
            })
            changeValue(c)
            return temp.showTime + '<br />' + str
        },
    },
    // 网格间距设置
    grid: {
        top: '40px',
        bottom: '50px',
        left: '60px',
        right: '60px',
        containLabel: true
    },
    dataZoom: [
        {
            type: 'slider',
            show: true,
            brushSelect: false,
            xAxisIndex: [0],
        },
        {
            type: 'slider',
            show: true,
            brushSelect: false,
            yAxisIndex: [0],
            left: '0%',
        },
        {
            type: 'inside',
            xAxisIndex: [0],
        },
        {
            type: 'inside',
            yAxisIndex: [0],
        }
    ],
    xAxis: {
        // xAxis的下不在设置data属性共享时间`
        type: 'time',
        splitLine: { show: true },
        lineStyle: {
            width: 2
        },
        axisTick: {
            show: false
        },
        axisLabel: {
            // 设置坐标轴上的时间格式
            formatter: function (value) {
                // console.log('时间戳', value)
                // 将时间转换为 JavaScript 日期对象  
                return backTime(value)
            },
            showMinLabel: true,
            showMaxLabel: true // 固定显示X轴的最后一条数据
        },
        // 更改x轴线的颜色
        axisLine: {
            lineStyle: {
                color: '#D2DBE6;',
                width: 1 // x轴线的宽度
            }
        },
    },
    yAxis: {
        type: 'value',
        splitLine: { show: true }
    }
}

onMounted(async () => {
    nowTime.value = formatTime(new Date());
    setInterval(() => {
        nowTime.value = formatTime(new Date());
    }, 1000);
    function $(el, all = false) {
        if (all) return document.querySelectorAll(el);
        return document.querySelector(el);
    }
    // 基于准备好的dom，初始化echarts实例
    myChart = echarts.init(document.getElementById("history_echarts"), 'dark');

    myChart.setOption(optionObj)

    myChart.on('tooltip', function (params) {
        // params 包含了当前鼠标所在的数据点信息
        var seriesData = params.data; // 获取当前鼠标所在的数据点
        console.log(seriesData);
    });

    // 请求接口的
    await setSdzListData()
    if (sdzOptions.length > 0) {
        // searchData.sdzs.push(0, 1, 2, 3)
        // searchHistoryData()
    }
//  页面加载动画
// doAjax()
});

const sdzOptions = reactive([])

// 设置SDZ数据
const setSdzListData = async () => {
    let sdzRes = await getSDZlist2();
    if (sdzRes.status !== 200) {
        return
    }
    sdzOptions.push(...sdzRes.data)
}

const resultTableData = reactive([])

function backTime(value) {
    let date = new Date(value);
    // 获取年份、月份和日期  
    let year = date.getFullYear();
    let month = date.getMonth() + 1; // 月份从 0 开始，需要加 1  
    let day = date.getDate();

    let hours = date.getHours();
    let minutes = date.getMinutes();
    let seconds = date.getSeconds();

    // 格式化月份和日期为两位数（不足两位时补零）  
    month = month < 10 ? '0' + month : month;
    day = day < 10 ? '0' + day : day;

    hours = hours < 10 ? '0' + hours : hours;
    minutes = minutes < 10 ? '0' + minutes : minutes;
    seconds = seconds < 10 ? '0' + seconds : seconds;

    // 返回格式化后的字符串  
    return year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds;
}

const multipleTableRef = ref(null)

let setInitSelected = true
// 历史曲线查询
const searchHistoryData = async (isDialog = false) => {
    timeoutCounter = -1
    clearTimeout(timeoutCounter)
    let params = JSON.parse(JSON.stringify(searchData));
    if (params.type === 1) {
        params.startTime = formatDate(timeRange.value[0])
        params.endTime = formatDate(timeRange.value[1])
    }
    if (isDialog === true) {
        params.sdzs = [...selectSDZArr]
    } else {
        if (!params.sdzs || params.sdzs.length < 1) {
            ElMessage({
                type: 'warning',
                message: `请选择特征值信息！`,
            })
            return;
        } else {
            const sdzsTemp = []
            params.sdzs.forEach(i => {
                sdzsTemp.push({
                    seq: sdzOptions[i].seq,
                    table0: sdzOptions[i].table0,
                    column0: sdzOptions[i].column0,
                    description: sdzOptions[i].description,
                })
            })
            params.sdzs = sdzsTemp
        }
    }
    loading.value = true
    let res = await history(params);
    console.log(res);
    loading.value = false
    if (res.status === 200) {
        myChart.clear();
        setInitSelected = true
        // const tempArr = selectSDZArr.slice(resultTableData.length)
        resultTableData.length = 0
        serieData.length = 0
        legendData.length = 0
        res.data.forEach((item, i) => {
            if (isDialog !== true) {
                selectSDZArr.length = 0
                searchData.sdzs?.forEach(i => {
                    selectSDZArr.push({ seq: searchData.sdzs[i], ...sdzOptions[i] })
                })
            }
            resultTableData.push(item)
            let description = item.description = item.description || `description_${selectSDZArr[i]?.seq}`
            legendData.push({ name: description })
            serieData.push({
                "name": description,
                "type": "line",
                "symbol": "none",
                "connectNulls": true,
                "showAllSymbol": true,
                // 让每一条折线拥有数据自己的时间
                "data": item.avgs.map(item => [item.t, item.avg]),
                "unit": "%",
                "markPoint": {
                    "symbol": "rect",
                    "symbolSize": "12",
                    "label": { "show": false },
                    "tooltip": { "triggerOn": "click", "trigger": "item" },
                }
            })
        });
        myChart.setOption(optionObj)
        myChart.setOption({
            series: serieData,
            legend: {
                data: legendData
            },
            yAxis: {
                max: (res.data[0] && res.data[0].max0) ? res.data[0].max0 : 4000,
                min: 0,
            }
        })
        nextTick(() => {
            multipleTableRef.value.toggleAllSelection()
            myChart.getOption()
        })
    } else if(res.status === 501) {
        ElMessage({
                type: 'error',
                message: res.message,
                offset: window.screen.height / 3,
               
        })
        return;
    } else if(res.status === 502) {
        ElMessage({
                type: 'error',
                message: res.message,
                offset: window.screen.height / 3,
               
        })
        return;
    }
};

const handleSelectionChange = (selection) => {
    const legendSelected = {}
    legendData.forEach((item, i) => {
        if (selection.find(
            row => {
                if (row.description) {
                    return row.description === item.name
                } else {
                    return row.seq == item.name.split('_')[1]
                }
            })
        ) {
            legendSelected[item.name] = true
        } else {
            legendSelected[item.name] = false
        }
    })
    myChart.setOption({ legend: { selected: legendSelected } })
}

const poperStyle = reactive({
    left: 0,
    top: 0,
    bottom: 'unset',
})

const popOverVisible = ref(false)
// 添加或删除 sdz
const currentClickNo = ref(-1)
const addOrDelete = (row, col, $event) => {
    $event.preventDefault();
    popOverVisible.value = true
    poperStyle.left = $event.pageX + 'px'
    // poperStyle.top = $event.pageY + 'px'
    // poperStyle.left = $event.clientX + 'px'
    poperStyle.top = ($event.y - 55) + 'px'
    currentClickNo.value = row.seq

    let clickHiddenEventFunc = function () {
        popOverVisible.value = false
        document.removeEventListener('click', clickHiddenEventFunc)
    }
    clickHiddenEventFunc = document.addEventListener('click', clickHiddenEventFunc)

}
const toAddSDZ = () => {
    dialogVisible.value = true
    
    // nextTick(() => {
    //     if (setInitSelected) {
    //         dialogTableComp.value.toggleAllSelection()
    //         nextTick(() => {
    //             dialogTableComp.value.getSelectionRows().forEach(row => {
    //                 if (selectSDZArr.find(item => item.seq === row.seq)) {
    //                     dialogTableComp.value.toggleRowSelection(row, true)
    //                 } else {
    //                     dialogTableComp.value.toggleRowSelection(row, false)
    //                     console.log(row.seq)
    //                 }
    //             })
    //         })
    //         setInitSelected = false
    //     }
    // })
}
const toDeleteSDZ = () => {
    if (currentClickNo.value > -1) {
        let deleteIndex = 0
        selectSDZArr.forEach((item, i) => {
            if (item.seq === currentClickNo.value) {
                deleteIndex = i
            }
        })
        selectSDZArr.splice(deleteIndex, 1)
        searchData.sdzs = searchData.sdzs.filter(i => sdzOptions[i].seq !== currentClickNo.value)
        currentClickNo.value = -1
        searchHistoryData(true)
    }
}

const changeMinMax = (row, col) => {
    if (col.type === 'selection') return
    myChart.setOption({
        yAxis: {
            max: Number(row.max0),
            min: Number(row.min),
        }
    })
}
const filterValue = ref('')
const dialogVisible = ref(false)

watch(
    () => dialogVisible.value,
    (newVal) => {
        if (newVal) {
            dialogTableData.length = 0
            dialogTableData.push(...sdzOptions)
        }
    }
)

// 模糊查询点表
const dialogTableData = reactive([])
const toSearchSdz = () => {
    searchSdz(filterValue.value).then(res => {
        if (res.status === 200) {
            dialogTableData.length = 0
            dialogTableData.push(...res.data)
        }
    })
}

const dialogTableComp = ref(null)
// 弹窗确认按钮
const toConfirmDialog = () => {
    const rows = dialogTableComp.value.getSelectionRows()
    selectSDZArr.push(...rows)
    searchHistoryData(true)
    dialogVisible.value = false
}
      
</script>


<style lang="scss" scoped>
.el-message .el-message__content {
    padding: 15px; /* 设置内边距 */
  }

  .custom-message-style {
    background-color: #f0edd4 !important;
    .el-icon-info::before {
        color: #f0edd4 !important;
        
    }
    .el-message__content {
        color: #dd7b11 ;
        font-size: 50px;
    }
  }
.outer-container {
    position: relative;
    top: 55px;
    min-width: 1800px;
    height: calc(100vh - 55px);
    // background-color: #FFF;
    color: #000;
    background-color: #042c45;
    // background-color: #8ea1a8;

    .search-form-panel {
        padding: 20px 100px;
        background-color: #042c45;

        .el-form {
            display: flex;
            justify-content: flex-start;
            align-items: center;
            flex-wrap: wrap;

            &:last-child {
                .el-form-item {
                    margin-bottom: 0;
                }
            }

            .el-form-item {
                margin-bottom: 10px;
                color: #FFF;

                &:deep(.el-form-item__label) {
                    --el-text-color-regular: #FFF;
                }
            }

            .sdz-select:deep(.el-select__popper ul.el-scrollbar__view.el-select-dropdown__list) {
                width: 80vw;
                height: 50vh;
                display: flex;
                flex-wrap: wrap;
            }

            .sdz-select:deep(.el-select__popper ul.el-scrollbar__view.el-select-dropdown__list>li) {
                /* width: 200px; */
                flex: 20% 0 1;
                border-right: 1px solid #ccc;
            }

            .sdz-select:deep(.el-select-dropdown__wrap) {
                max-height: 50vh;
            }

            .sdz-select:deep(.el-select-dropdown.is-multiple .el-select-dropdown__item.is-selected::after) {
                left: 20px;
                right: unset;
            }

            .sdz-select:deep(.el-select-dropdown.is-multiple .el-select-dropdown__item::before) {
                content: "";
                position: absolute;
                top: 50%;
                border: 1px solid #ccc;
                width: 14px;
                height: 14px;
                left: 18px;
                right: unset;
                border: 1px solid #606266;
                transform: translateY(-50%);
            }

            .sdz-select:deep(.el-select-dropdown__item) {
                padding-left: 40px;
            }
        }
    }

    .echarts-panel {
        width: 80%;
        margin: 0 auto;
        background-color: #100c2a;
        height: 500px;
        padding-top: 20px;
    }

    .result-table-panel {
        height: 200px;
        width: 100%;
        display: flex;
        justify-content: center;
        align-items: center;

        >.el-table {
            background-color: #100c2a;

            &:deep(.cell) {
                text-wrap: nowrap;
            }

            $colorArr: #5470c6, #91cc75, #fac858, #ee6666, #73c0de, #3ba272, #fc8452, #9a60b4, #ea7ccc;

            @for $i from 1 through length($colorArr) {
                :deep(tr.el-table__row:nth-child(9n + #{$i})) {

                    .cell,
                    .el-input__inner {
                        color: nth($colorArr, $i);
                    }
                }
            }

            &:deep(.el-table__cell) {
                background-color: #100c2a;
            }

            .el-input:deep(.el-input__wrapper) {
                box-shadow: unset;
                background-color: #100c2a;

                &.is-focus {
                    box-shadow: 0 0 0 1px var(--el-input-border-color, var(--el-border-color)) inset;
                    background-color: #FFF;
                }
            }
        }

        .popover-container {
            position: absolute;
            width: 80px;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            z-index: 10;
            background-color: #FFF;
            border: 1px solid #CCC;
            box-sizing: content-box;
            padding: 2px 2px;
            border-radius: 2px;

            span {
                display: inline-block;
                box-sizing: content-box;
                width: 80px;
                font-size: 12px;
                line-height: 26px;
                text-align: center;
                border-radius: 2px;
                color: #333;

                &:hover {
                    background-color: #008AFF;
                    color: #FFF;
                }
            }

        }
    }

}
</style>

<style lang="css">
.echarts-container{
    height: calc(100vh - 500px)
}
.stage_t a {
    height: 50px;
}

.stage_t {
    z-index: 1000;
}
body {
  margin: 0;
}
.example-showcase .el-loading-mask {
  z-index: 9;
}

</style>
